<template>
  <Card>
    <Row type="flex"
         align="top"
         justify="space-between">
      <Form ref="formSearch"
            class="sellPending"
            inline>
        <FormItem label="场馆"
                  v-if="!userInfo.storeId">
          <Select v-model="formSearch.storeId"
                  style="width:150px"
                  clearable>
            <Option v-for="(item, index) in storeIdList"
                    :key="index"
                    :value="item.id">{{item.storeName}}</Option>
          </Select>
        </FormItem>
        <FormItem label="卡名称">
          <Select v-model="formSearch.cardName"
                  style="width:200px"
                  filterable
                  remote
                  clearable
                  :remote-method="remoteMethod1"
                  :loading="loading1"
                  placeholder="输入卡名称筛选">
            <Option v-for="(option, index) in options1"
                    :value="option.label"
                    :key="index">{{option.label}}</Option>
          </Select>
        </FormItem>
        <FormItem label="手机/姓名">
          <Row>
            <Col span="18">
            <Input clearable
                   placeholder="输入手机/姓名搜索"
                   class="search-input"
                   v-model="formSearch.member" />
            </Col>
            <Col span="4"
                 offset="1">
            <Button @click="expenseList"
                    class="search-btn"
                    type="primary">
              <Icon type="search" />搜索</Button>
            </Col>
          </Row>

        </FormItem>
      </Form>
      <Button class="margin-b-20"
              icon="md-add"
              type="primary"
              @click="expenseModal = true">发卡</Button>
    </Row>
    <Table border
           :loading="tableLoading"
           :columns="expenseListColumns"
           :data="expenseColumns">
    </Table>
    <Row type="flex"
         class="margin-t-20">
      <Page :total="pageTotal"
            @on-change="changePage" />
    </Row>
    <Modal v-model="expenseModal"
           title="发卡"
           :loading="loading"
           :mask-closable="false"
           @on-ok="onExpenseSubmit"
           @on-visible-change="onAddExpenseVisible">
      <Form :model="expense"
            ref="expenseForm"
            :rules="ruleValidate"
            :label-width="100">
        <FormItem label="手机"
                  prop="member">
          <Input v-model="expense.member"
                 style="width:300px"
                 search
                 enter-button
                 @on-search="getByPhone"
                 placeholder="输入手机号码查找用户信息" />
          <span class="demo-data">{{seachText}}</span>
        </FormItem>
        <FormItem label="场馆"
                  v-if="!userInfo.storeId">
          <Select v-model="expense.storeId"
                  style="width:150px"
                  clearable>
            <Option v-for="(item, index) in storeIdList"
                    :key="index"
                    :value="item.id">{{item.storeName}}</Option>
          </Select>
        </FormItem>
        <FormItem label="发卡员"
                  prop="sendCardUser">
          <Select v-model="expense.sendCardUser"
                  style="width:200px"
                  clearable>
            <Option v-for="(item, index) in staffList"
                    :key="index"
                    :value="item.nickname">{{item.nickname}}</Option>
          </Select>
        </FormItem>
        <FormItem label="卡名称"
                  prop="cards">
          <Select v-model="expense.cards"
                  filterable
                  multiple
                  remote
                  :remote-method="remoteMethod2"
                  :loading="loading2"
                  style="width:200px">
            <Option v-for="item in options2"
                    :value="item.value"
                    :key="item.value">{{ item.label }}</Option>
          </Select>
        </FormItem>
        <FormItem label="发卡时间"
                  prop="sendTimeStr">
          <DatePicker v-model="expense.sendTimeStr"
                      @on-change="changeSendTime"
                      type="date"
                      placeholder="会员卡发卡时间"
                      style="width: 200px"></DatePicker>
        </FormItem>
        <FormItem label="过期时间"
                  prop="endTimeStr">
          <DatePicker v-model="expense.endTimeStr"
                      @on-change="changeEndTime"
                      type="date"
                      placeholder="会员卡到期时间"
                      style="width: 200px"></DatePicker>
        </FormItem>
        <FormItem label="已消费"
                  prop="consumption">
          <Input v-model="expense.consumption"
                 style="width: 200px;">
          <Select v-model="expense.consumptionType"
                  style="width: 50px;"
                  slot="append">
            <Option :value="0">元</Option>
            <Option :value="1">次</Option>
          </Select>
          </Input>
        </FormItem>
        <FormItem label="备注">
          <Input v-model="expense.remarks"
                 clearable
                 maxlength="100"
                 show-word-limit
                 type="textarea"
                 placeholder="请输入备注"
                 style="width: 200px" />
        </FormItem>
      </Form>
    </Modal>
    <Modal title="会员详情"
           :mask-closable="false"
           fullscreen
           scrollable
           v-model="detailsModal">
      <member-details ref="detailsModal"></member-details>
      <div slot="footer">
        <Button type="error"
                size="large"
                long
                @click="detailsModal = false">关闭</Button>
      </div>
    </Modal>
  </Card>

</template>
<script>
import memberDetails from '../members/components/member-details'
import { expenseList, addExpense, deleteExpense } from '@/api/expense'
import { addMemberCard } from '@/api/card'
import { getByPhone } from '@/api/user'
import { cardList } from '@/api/setting-course'
import { storeAll } from '@/api/setting-shop'
import { staffList } from '@/api/setting-staff'
import { mapActions, mapGetters } from 'vuex'
export default {
  components: {
    memberDetails
  },
  data () {
    return {
      detailsModal: false,
      expenseModal: false,
      loading: true,
      tableLoading: false,
      // 弹框
      expense: {
        member: '',
        storeId: 0,
        sendCardUser: '',
        sendTimeStr: 0,
        endTimeStr: '',
        consumptionType: 0,
        remarks: ''
      },
      // 场馆列表
      storeIdList: [],
      // 店员列表
      staffList: [],
      // 会员卡列表
      cardNameList: [],
      // 会员卡对象
      cardNameObj: {},
      // 消费会员卡信息
      seachInfoCards: [],
      seachText: '',
      ruleValidate: {
        cardName: [{ required: true, message: '请入会员卡名称', trigger: 'blur' }],
        member: [{ required: true, message: '请入手机号码', trigger: 'blur' }],
        consumption: [{ required: true, message: '请入消费金额/次数', trigger: 'blur' }]
      },
      pageTotal: 0,
      expenseListColumns: [
        {
          title: '姓名',
          key: 'name',
          fixed: 'left',
          minWidth: 100
        },
        {
          title: '电话',
          key: 'phone',
          minWidth: 140
        },
        {
          title: '发卡馆',
          key: 'storeId',
          minWidth: 140,
          render: (h, params) => {
            for (let i of this.storeIdList) {
              if (params.row.storeId === i.id) {
                return h(
                  'span',
                  {},
                  i.storeName
                )
              }
            }
          }
        },
        {
          title: '卡名称',
          key: 'cardName',
          minWidth: 140
        },
        {
          title: '卡余额',
          key: 'money',
          minWidth: 100
        },
        {
          title: '操作人',
          key: 'action',
          minWidth: 100
        },
        {
          title: '发卡时间',
          key: 'createTime',
          minWidth: 100
        },
        {
          title: '到期时间',
          key: 'createTime',
          minWidth: 100
        },
        {
          title: '操作',
          key: 'action',
          width: 150,
          fixed: 'right',
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h('Button', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.detailsModal = true
                    this.$refs.detailsModal.getByPhone(params.row.phone)
                  }
                }
              }, '详情'),
              h('Button', {
                props: {
                  type: 'error',
                  size: 'small'
                },
                on: {
                  click: () => {
                    this.deleteExpense(params.row.id)
                  }
                }
              }, '删除')
            ])
          }
        }
      ],
      expenseColumns: [],
      // 筛选条件
      formSearch: {
        cardName: '',
        size: 10,
        page: 1,
        member: '',
        storeId: 0
      },
      model13: '',
      loading1: false,
      options1: [],
      list: [],
      reseIndex: 0,
      startValue: '',
      endValue: ''
    }
  },
  computed: {
    formatStartNumber () {
      if (this.startValue === '') return '请输入金额'
      function parseNumber (str) {
        const re = /\d{1,3}(?=(\d{3})+(\.|$))/g
        return str.replace(re, '$&,')
      }
      return parseNumber(this.startValue)
    },
    formatEndNumber () {
      if (this.endValue === '') return '请输入金额'
      function parseNumber (str) {
        const re = /\d{1,3}(?=(\d{3})+(\.|$))/g
        return str.replace(re, '$&,')
      }
      return parseNumber(this.endValue)
    },
    ...mapGetters([
      'userInfo'
    ])
  },
  async created () {
    if (this.userInfo.storeId) {
      this.$set(this.expense, 'storeId', this.userInfo.storeId)
      this.$set(this.formSearch, 'storeId', this.userInfo.storeId)
    }
    await this.cardList()
    await this.getStaffList()
    await this.storeAll()
    await this.expenseList()
  },
  methods: {
    storeAll () { // 场馆列表
      return new Promise((resolve, reject) => {
        storeAll().then(res => {
          this.storeIdList = res.data
          resolve(res.data)
        })
      })
    },
    getStaffList () { // 店员列表
      return new Promise((resolve, reject) => {
        staffList({ size: 200, storeId: this.formSearch.storeId }).then(res => {
          this.staffList = res.data.rows
          resolve(res.data.rows)
        })
      })
    },
    cardList () { // 卡列表
      cardList({
        name: '',
        type: '',
        varieties: ''
      }).then(res => {
        this.cardNameList = res.data
        res.data.forEach(e => {
          this.cardNameObj['card' + e.id] = e
        })
      })
    },
    expenseList () {
      this.tableLoading = true
      expenseList(this.formSearch).then(res => {
        this.expenseColumns = res.data.records
        this.pageTotal = res.data.total
        this.tableLoading = false
      })
    },
    onAddExpenseVisible (visible) {
      // 弹框状态改变 清除默认值
      if (visible) return
      this.$refs['expenseForm'].resetFields()
    },
    onExpenseSubmit () {
      this.$refs['expenseForm'].validate(valid => {
        // eslint-disable-next-line no-useless-return
        setTimeout(() => {
          this.loading = false
        }, 300)
        setTimeout(() => {
          this.loading = true
        }, 400)
        if (!valid) return
        addMemberCard(this.expense).then(res => {
          this.$refs['expenseForm'].resetFields()
          this.expenseModal = false
          this.$Message.success('添加成功')
          this.expenseList()
        })
      })
    },
    deleteExpense (id) {
      this.$Modal.confirm({
        title: '提示',
        content: '确定删除？',
        loading: true,
        okText: '删除',
        onOk: () => {
          deleteExpense(id)
            .then(res => {
              this.$Modal.remove()
              this.$Message.success('删除成功')
              this.expenseList()
            })
            .catch(() => {
              this.$Modal.remove()
            })
        }
      })
    },
    remoteMethod1 (query) {
      if (query !== '') {
        this.loading1 = true
        setTimeout(() => {
          this.loading1 = false
          const cardNameList = this.cardNameList.map(item => {
            return {
              value: item.id,
              label: item.name
            }
          })
          this.options1 = cardNameList.filter(item => item.label.toLowerCase().indexOf(query.toLowerCase()) > -1)
        }, 200)
      } else {
        this.options2 = []
      }
    },
    getByPhone (val) {
      this.seachText = '正在查询...'
      getByPhone(val).then(res => {
        this.seachText = res.data.realname
        this.seachInfoCards = res.data.cards
      }).catch(() => {
        this.seachText = '查询失败'
      })
    },
    changeCardType (item) {
      const type = this.cardNameObj['card' + item].type
      this.$set(this.expense, 'consumptionType', type === 1 ? 0 : 1)
      this.$set(this.expense, 'cardName', this.cardNameObj['card' + item].name)
    },
    changePage (val) {
      this.formSearch = { ...this.formSearch, page: val }
      this.expenseList()
    }
  }
}
</script>
<style lang="less">
.sellPending {
  flex: 1;
  .search-item {
    display: flex;
    margin-bottom: 10px;
    .search-btn {
      margin-left: 20px;
    }
  }
}
.receiverTypeTip {
  text-align: center;
  overflow: hidden;
  &-title {
    margin-bottom: 5px;
  }
  &-img {
    width: 200px;
    overflow: hidden;
    img {
      width: 100%;
      height: auto;
    }
  }
}
.confirmRemberModalRow {
  margin-bottom: 10px;
}
.loading-drop-down {
  display: flex;
  align-items: center;
  padding: 2px 16px;
  background-color: #f2f6fa;
  color: #357ce1;
  border-radius: 2px;
}
</style>
